﻿/****************************************************************************************************************************
*	global variable
****************************************************************************************************************************/
var map;
var markers = new fMarkers();
// **************************************************************************************************************************





/****************************************************************************************************************************
*	functions call once when page loaded
****************************************************************************************************************************/
function DrawGoogleMap() {
//    var latlng = new google.maps.LatLng(-34.397, 150.644);
//    var myOptions = {
//        zoom: 8,
//        center: latlng,
//        mapTypeId: google.maps.MapTypeId.ROADMAP
//    };

//    map = new google.maps.Map(document.getElementById("GoogleMap_Div"), myOptions);

    Service.GetGoogleMapObject(GetGoogleMapObjectHandler);
}

function GetGoogleMapObjectHandler(result) {

    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: result.ZoomLevel,
        center: new google.maps.LatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude),
         //center:new google.maps.LatLng(37.339085, -121.8914807),
        //mapTypeId: 'satellite',
        //mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeId: result.StringMapType,
        panControl: result.PanControl,
        zoomControl: result.ZoomControl,
        mapTypeControl: result.MapTypeControl,
        scaleControl: result.ScaleControl,
        streetViewControl: result.StreetViewControl,
        overviewMapControl: result.OverviewMapControl
    };
    
    map = new google.maps.Map(document.getElementById("GoogleMap_Div"), myOptions);
    //map.setTilt(45);
    //map.setHeading(90);

//    var bikeLayer = new google.maps.BicyclingLayer();
//    bikeLayer.setMap(map);

//    //var panoramioLayer = new google.maps.panoramio.PanoramioLayer();
//    //panoramioLayer.setMap(map);
////    var panoramioLayer = new google.maps.panoramio.PanoramioLayer();
////    panoramioLayer.setMap(map);
//    var trafficLayer = new google.maps.TrafficLayer();
//trafficLayer.setMap(map);
//var layer = new google.maps.FusionTablesLayer({
//  query: {
//    select: 'address',
//    from: '198945',
//    //where: 'ridership > 5000'
//  }
//});
//layer.setMap(map);


//var georssLayer = new google.maps.KmlLayer('http://api.flickr.com/services/feeds/geo/?g=322338@N20&lang=en-us&format=feed-georss');
//georssLayer.setMap(map);

//layer = new google.maps.FusionTablesLayer({
//  query: {
//    select: 'LATITUDE',
//    from: '136705'
//  },
//  heatmap: {
//    enabled: true
//  }
//});
//layer.setMap(map);

     // Create the DIV to hold the control and call the HomeControl() constructor
  // passing in this DIV.
  //if(result.CountControlsCurrent > result.CountControlsOld)
  for(i=0;i<result.CountControlsCurrent;i++)
  {
        var ControlDiv = document.createElement('DIV');
        var customControl = new CustomControl(result.Controls[i], i, ControlDiv, map);
        ControlDiv.index = i+1;
        map.controls[result.Controls[i].position].push(ControlDiv);
  }

  var styleArray = new Array();
  for(i=0;i<result.CountStyleCurrent;i++)
  {
    var style = CreateStyle(result.Styles[i]);
    styleArray.push(style);
  }
  map.setOptions({styles: styleArray});

//  var ControlDiv = document.createElement('DIV');
//  var Control = new CustomControl(homeControlDiv, map);

//  homeControlDiv.index = 1;
//  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);


    //map.setCenter(new google.maps.LatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude));
    map.setZoom(result.ZoomLevel);
    google.maps.event.addListener(map, 'click', function (event) {
        MapClickFunction(event.latLng);
    });

    google.maps.event.addListener(map, 'dblclick', function (event) {
        MapDBClickFunction(event.latLng);
    });

//    google.maps.event.addListener(map, 'mouseup', function (event) {
//        MouseUpFunction(event.latLng);
//    });

//    google.maps.event.addListener(map, 'mousedown', function (event) {
//        MouseDownFunction(event.latLng);
//    });

//    google.maps.event.addListener(map, 'mouseover', function (event) {
//        MouseOverFunction(event.latLng);
//    });

//    google.maps.event.addListener(map, 'mouseout', function (event) {
//        MouseOutFunction(event.latLng);
//    });

//    google.maps.event.addListener(map, 'zoom_changed', function () {
//        Zoom_Changed();
//    });

//    google.maps.event.addListener(map, 'center_changed', function () {
//        Center_Changed();
//    });

//    google.maps.event.addListener(map, 'bound_changed', function () {
//        Bound_Changed();
//    });
    
    for (i = 0; i < result.Markers.length; i++) {
        var markerIcon = null;
        var shadowMarkerIcon = null; 
        //Marker icon
        if (result.Markers[i].IconImage != '') {
            markerIcon = new google.maps.MarkerImage(result.Markers[i].IconImage,
                                                  new google.maps.Size(result.Markers[i].IconImageWidth, result.Markers[i].IconImageHeight),
                                                  new google.maps.Point(0, 0),
                                                        // The anchor for this image is the base of the flagpole at 0,32.
                                                  new google.maps.Point(result.Markers[i].IconAnchor_posX, result.Markers[i].IconAnchor_posY));
        }
        if (result.Markers[i].IconShadowImage != '') {
            shadowMarkerIcon = new google.maps.MarkerImage(result.Markers[i].IconShadowImage,
                                                // The shadow image is larger in the horizontal dimension
                                                // while the position and offset are the same as for the main image.
                                                  new google.maps.Size(result.Markers[i].IconShadowWidth, result.Markers[i].IconShadowHeight),
                                                  new google.maps.Point(0, 0),
                                                  new google.maps.Point(result.Markers[i].IconAnchor_posX, result.Markers[i].IconAnchor_posY));
        }
        var marker = CreateMarker(result.Markers[i].Latitude, result.Markers[i].Longitude, markerIcon, shadowMarkerIcon,result.Markers[i].InfoHTML, result.Markers[i].Draggable, result.Markers[i].ToolTip);
        marker.value = result.Markers[i].ID;
        markers.pushValue(marker);
        markers.getLastValue().setMap(map);
        
    }
}
// **************************************************************************************************************************


/****************************************************************************************************************************
*	functions call regularly 
****************************************************************************************************************************/

function GetGoogleMapObjecOptimizetHandler(result) {

//     if(map.center.lat() != result.CenterPoint.Latitude || map.center.lng() != result.CenterPoint.Longitude)
//          map.setCenter(new google.maps.LatLng(result.CenterPoint.Latitude, result.CenterPoint.Longitude));
    for (i = 0; i < result.Markers.length; i++) {

        
        //Marker icon 
        var markerIcon = null;
        var shadowMarkerIcon = null;
        if (result.Markers[i].IconImage != '') {
            markerIcon = new google.maps.MarkerImage(result.Markers[i].IconImage,
                                                  new google.maps.Size(result.Markers[i].IconImageWidth, result.Markers[i].IconImageHeight),
                                                  new google.maps.Point(0, 0),
                                                        // The anchor for this image is the base of the flagpole at 0,32.
                                                  new google.maps.Point(result.Markers[i].IconAnchor_posX, result.Markers[i].IconAnchor_posY));
        }
        if (result.Markers[i].IconShadowImage != '') {
            shadowMarkerIcon = new google.maps.MarkerImage(result.Markers[i].IconShadowImage,
                                                // The shadow image is larger in the horizontal dimension
                                                // while the position and offset are the same as for the main image.
                                                  new google.maps.Size(result.Markers[i].IconShadowWidth, result.Markers[i].IconShadowHeight),
                                                  new google.maps.Point(0, 0),
                                                  new google.maps.Point(result.Markers[i].IconAnchor_posX, result.Markers[i].IconAnchor_posY));
        }


        //Check Markers status
        ////---------Existing marker, but changed.
//        if(result.Markers[i].PointStatus=='C'){
//            var marker = markers.getValueById(result.Markers[i].ID);
//            if(marker!=null)
//            {
//                markers.removeValueById(result.Markers[i].ID);
//                marker.setMap(null);
//                
//            }
//            var marker = CreateMarker(result.Markers[i].Latitude, result.Markers[i].Longitude, markerIcon, shadowMarkerIcon, result.Markers[i].InfoHTML, result.Markers[i].Draggable, result.Markers[i].ToolTip);
//            marker.value = result.Markers[i].ID;
//            markers.pushValue(marker);
//            markers.getLastValue().setMap(map);//set overlay map
//        }

        //New marker
        if (result.Markers[i].PointStatus == 'N'){
             var marker = CreateMarker(result.Markers[i].Latitude, result.Markers[i].Longitude, markerIcon, shadowMarkerIcon, result.Markers[i].InfoHTML, result.Markers[i].Draggable, result.Markers[i].ToolTip);
             marker.value = result.Markers[i].ID;
             markers.pushValue(marker);
             markers.getLastValue().setMap(map);
         }

        //Existing marker, but deleted.
//        if(result.Markers[i].PointStatus=='D'){
//            var marker = markers.getValueById(result.Markers[i].ID);
//            if(marker!=null)
//            {
//                markers.removeValueById(result.Markers[i].ID);
//                marker.setMap(null);
//            }
//        }
     }
}

function endRequestHandler(sender, args) {
    Service.GetOptimizedGoogleObject(GetGoogleMapObjecOptimizetHandler);
}

function pageLoad() {
    if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}

// **************************************************************************************************************************




/****************************************************************************************************************************
*	functions 
****************************************************************************************************************************/
function MapClickFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseClick', latlng.lat() + "," + latlng.lng());
    }
}

function MapDBClickFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseDoubleClick', latlng.lat() + "," + latlng.lng());
    }
}

function MouseUpFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseUp', latlng.lat() + "," + latlng.lng());
    }
}

function MouseDownFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseDown', latlng.lat() + "," + latlng.lng());
    }
}

function MouseOverFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseOver', latlng.lat() + "," + latlng.lng());
    }
}

function MouseOutFunction(latlng) {
    if (latlng) {
        RaiseEvent('MouseOut', latlng.lat() + "," + latlng.lng());
    }
}

function Zoom_Changed() {
    RaiseEvent('ZoomChanged', "");
}
function Center_Changed() {
    RaiseEvent('CenterChanged', "");
}
function Bound_Changed() {
    RaiseEvent('BoundChanged', "");
}


function PlaceMarker(latitude, longitude) {
    var position = new google.maps.LatLng(latitude, longitude);

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP,
        position: position
    });
}

function CreateMarker(latitude, longitude, icon, iconShadow, InfoHTML, bDraggable, sTitle) {
    var position = new google.maps.LatLng(latitude, longitude);

    var infowindow = new google.maps.InfoWindow({
        content: InfoHTML
    });

    var marker = new google.maps.Marker({
        map: map,
        draggable: bDraggable,
        animation: google.maps.Animation.DROP,
        position: position,
        title: sTitle,
        shadow: iconShadow,
        icon: icon,

    });

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
        RaiseEvent('MarkerClicked', this.value);
    });

    google.maps.event.addListener(marker, 'dragend', function () {
        RaiseEvent('MarkerDrag', this.value);
    });
    return marker;
}


function CustomControl(control, index, controlDiv, map) {

  // Set CSS styles for the DIV containing the control
  // Setting padding to 5 px will offset the control
  // from the edge of the map
  controlDiv.style.padding = '5px';

  // Set CSS for the control border
  var controlUI = document.createElement('DIV');
  controlUI.style.backgroundColor = control.BackgroundColor;
  controlUI.style.borderStyle = control.BorderStyle;
  controlUI.style.borderWidth = control.BorderWidth;
  controlUI.style.cursor = control.Cursor;
  controlUI.style.textAlign = control.TextAlign;
  controlUI.title = control.Title;
  controlDiv.appendChild(controlUI);

  // Set CSS for the control interior
  var controlText = document.createElement('DIV');
  controlText.style.fontFamily = control.FontFamily;
  controlText.style.fontSize = control.FontSize;
  controlText.style.paddingLeft = control.PaddingLeft;
  controlText.style.paddingRight = control.PaddingRight;
  controlText.innerHTML = control.InnerHTML;
  controlUI.appendChild(controlText);

  // Setup the click event listeners: simply set the map to Chicago
  google.maps.event.addDomListener(controlUI, 'click', function() {
    //RaiseEvent('ControlClicked', index);
  });
}

function CreateStyle(style)
{
return  {   
            featureType: style.Feature,
            elementType: style.Element,
            stylers: [
                        { gamma: style.gamma },
                        { hue: style.hue },
                        { invert_lightness: style.invert_lightness },
                        { saturation: style.saturation },
                        { lightness: style.lightness },
                        { visibility: style.visibility }
                    ]
       }
}

// **************************************************************************************************************************

function fMarkers() {
    this.markers = new Array();
    this.getLength = function() { return this.markers.length; };
    this.pushValue = function(v) { this.markers.push(v); }
    this.getValue = function(i) { return this.markers[i]; }
    this.getLastValue = function() { return this.markers[this.markers.length - 1]; }
    this.getValueById = function(ID) {
        var i;
        for (i = 0; i < this.markers.length; i++) {
            if (this.markers[i].value == ID) {
                // alert('marker found : '+this.markers[i].value);
                return this.markers[i];
            }
        }
        return null;
    }
    this.removeValueById = function(ID) {
        var i;
        for (i = 0; i < this.markers.length; i++) {
            if (this.markers[i].value == ID) {
                // alert('marker found : '+this.markers[i].value);
                this.markers.splice(i, 1);
                //alert('changed marker removed');

            }
        }
        return null;
    }
}